package com.admin.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author 吴驰明
 * @date 2023/7/17
 * @Description
 */
@Component
@Slf4j
@Data
public class MailUtils {
    @Value("${spring.mail.username}")
    private String from;
    private String subject = "三组管理系统";
    @Autowired
    private MailSender mailSender;
    @Lazy
    @Autowired
    private MailUtils mail;
    private boolean sendMessage(String to,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try{
            // 获取自己代理后的对象
            mail.sendAsync(message);
            return true;
        }catch (Exception e){
            log.error("{},发送失败",to);
            return false;
        }
    }
    public boolean sendRegisterCode(String to,String code){
        String content = "欢迎使用三组管理平台，您的注册验证码为："+code+"。请勿将改信息发送给其他人。";
        return sendMessage(to,content);
    }
    @Async
    public void sendAsync(SimpleMailMessage message){
        mailSender.send(message);
    }
}
